#include <soar.h>

#define THRD_NUM        1

struct thrd_ctl
{
    unsigned long thrd_id;
    int thrd_idx;
};

int transfer_size;

static THRD_FUNC(thrd_func, struct thrd_ctl, thrd_ctl)
{/*{{{*/
    MSGQ_SEND msgq;
    unsigned char *msg;
    int msg_size;
    int res;

#ifdef _MY_MULTI
    int count;

    ALLOC_MULTI_RETERR(msg, unsigned char, transfer_size+1, NULL);
    res=msgq_send_attach(&msgq);
    if(res)
    {
        fprintf(stderr, "%s: msgq_send_attach fail, res:%d\n",
                __func__, res);
        goto GO_OUT;
    } 

    count=0;
    while(count<100000)
    {
        memset(msg, '0', transfer_size);
        msg_size=transfer_size;
        res=msgq_send(msgq, "msgq_test_client", "msgq_test_server",
                0, msg, msg_size, 10*1000);
        if(res)
        {
            fprintf(stderr, "%s: msgq_send fail, res:%d\n",
                    __func__, res);
            goto GO_OUT;
        }
        count++;
        if(count % 10000 == 0)
            printf("%d finished\n", count);
    }
#else
    char *ptr;

    ALLOC_MULTI_RETERR(msg, unsigned char, BUFFER_SIZE*2, NULL);
    res=msgq_send_attach(&msgq);
    if(res)
    {
        fprintf(stderr, "%s: msgq_send_attach fail, res:%d\n",
                __func__, res);
        goto GO_OUT;
    } 

    while(fgets((char *)msg, BUFFER_SIZE, stdin) != NULL)
    {
        if((ptr=strchr((char *)msg, RTN)))  *ptr=ZERO;
        msg_size=strlen((char *)msg);
        printf("msg_in: %s\n", msg);
        res=msgq_send(msgq, "msgq_test_client", "msgq_test_server",
                0, msg, msg_size, 10*1000);
        if(res)
        {
            fprintf(stderr, "%s: msgq_send_attach fail, res:%d\n",
                    __func__, res);
            goto GO_OUT;
        }
    }
#endif

GO_OUT:
    free(msg);
    msgq_send_detach(msgq);
    return(NULL);
}/*}}}*/

int main(int argc, char *argv[])
{/*{{{*/
#ifdef _MY_MULTI
    struct thrd_ctl a_thrd_ctl[THRD_NUM];
    int thrd_idx;

    if(argc == 1)
        transfer_size=KB(1);
    else
        transfer_size=KB(atoi(argv[1]));

    thrd_idx=0;
    a_thrd_ctl[thrd_idx].thrd_idx=thrd_idx;
    for(thrd_idx=0; thrd_idx<THRD_NUM; thrd_idx++)
    {
        a_thrd_ctl[thrd_idx].thrd_idx=thrd_idx;
        if(thrd_create((THRD_FUNC_T)thrd_func,
                    (void *)&a_thrd_ctl[thrd_idx], 0,
                    &a_thrd_ctl[thrd_idx].thrd_id))
        {
            printf("thrd create fail\n");
            return(-1);
        }
        //sleep(1);
    }
    for(thrd_idx=0; thrd_idx<THRD_NUM; thrd_idx++)
    {
        thrd_join(a_thrd_ctl[thrd_idx].thrd_id);
    }
#else
    log_from_stdout("stdout");
    thrd_func(NULL);
#endif

    return(0);
}/*}}}*/
